package com.wanban.downloader.db.room

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import com.wanban.downloader.db.DownloadEntity

@Database(
    entities =
    [
        DownloadEntity::class
    ],
    version = 1
)
abstract class DownloadRoomUtils : RoomDatabase() {

    companion object {
        @Volatile
        private var INSTANCE: DownloadRoomUtils? = null

        fun initRoom(context: Context){
            if (INSTANCE == null) {
                INSTANCE = synchronized(this) {
                    INSTANCE ?: buildDatabase(context).also { INSTANCE = it }
                }
            }
        }

        fun getInstance(): DownloadRoomUtils {
            if (INSTANCE == null) {
                throw java.lang.NullPointerException("Room is need init!!!")
            }
            return INSTANCE!!
        }

        private fun buildDatabase(context: Context) = Room.databaseBuilder(
            context.applicationContext, DownloadRoomUtils::class.java,
            "Download.db"
        ).allowMainThreadQueries()
            .fallbackToDestructiveMigrationOnDowngrade()
            .allowMainThreadQueries()
//            .addMigrations(MIGRATION_1_2())
            .build()
    }

    abstract fun downloadDao(): DownloadDao

}
